package com.itcj;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;

import java.io.IOException;


public class test {
    //crud
    @Test
    public void test01() throws Exception {
        ZooKeeper zk = new ZooKeeper("192.168.72.141:2181", 5000, null);
        zk.create("/c","swk".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        zk.setData("/c","jkjkjkjk".getBytes(),-1);

        Stat stat = new Stat();
        byte[] data = zk.getData("/c", null, stat);
        System.out.println(new String(data,"utf-8"));
        zk.delete("/c",-1);
        System.out.println(stat.getVersion());
        zk.close();
    }

//并发时version为-1的作用，不受影响
    public static void main(String[] args) {
        test02();
    }
    public static  void test02(){
        for(int i=1;i<=12;i++){
          final   int j=i;
            if (i == 4 || i == 7 || i == 10) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
                System.out.println(j);
            Thread t = new Thread(new Runnable() {
                public void run() {
                    try {
                        ZooKeeper zk = new ZooKeeper("node01:2181",5000,null);
                        Stat stat = new Stat();
                        zk.getData("/b",null,stat);
                        int version = stat.getVersion();
                        zk.setData("/b","aa".getBytes(),-1);
                        zk.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            t.start();
        }
    }

//临时节点
    @Test
    public void test03() throws IOException, KeeperException, InterruptedException {
        ZooKeeper zooKeeper = new ZooKeeper("192.168.72.141:2181", 5000, null);
        //zooKeeper.create("/c","sjksjkk".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);
        byte[] data = zooKeeper.getData("/b", null, null);
        System.out.println("111");
        System.out.println(new String(data));
        zooKeeper.close();
    }
//写一个watcher，监控节点是否被修改
    @Test
    public void test04() throws Exception {
        final ZooKeeper zk = new ZooKeeper("node01:2181",5000,null);
        zk.getData("/b", new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                System.out.println("主人，代码被修改了");
                try {
                    zk.getData("/b",this,null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, null);
        while (true){
            Thread.sleep(1000);
        }

    }

}
